package com.web.app.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证和生成token
 * @author JMLF
 * @date 2022-10-08
 */
public class TokenUtil {
    private static String SEC_KEY = "@123456";
    private static JWTVerifier build = JWT.require(Algorithm.HMAC256("@123456")).build();

    public static String getToken(int expiresDate,Map<String, String> data){
        //计算过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,expiresDate);
        //生成 token 字符串
        String token = JWT.create()
                //token需要携带的数据
                .withPayload(data)
                //token设置的过期时间
                .withExpiresAt(calendar.getTime())
                //token的加密方式
                .sign(Algorithm.HMAC256(SEC_KEY));
        //返回token
        return token;
    }
    //获取数据
    public static String getItem(String token,String key){
        DecodedJWT verify = build.verify(token);
        Map<String, Claim> claims = verify.getClaims();
        return claims.get(key).asString();
    }

    public static String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIiLCJleHAiOjE2NjYxNDI3NzksInVzZXJuYW1lIjoiMSJ9.ftur2AQdw0hobk42kCZK5x_yRLMtyH_tuqCkpWcsPPI";
//
    public static void main(String[] args) {
        String username = getItem(token, "username");
        String id = getItem(token, "id");
        System.out.println(username);
        System.out.println(id);
    }

}
